package com.soft.base.misc;

import lombok.extern.slf4j.Slf4j;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * class
 *
 * @author user
 * @date 2020/06/05
 */
@Slf4j
public class LotteryPool<T> {

    List<T> items = new ArrayList<T>();
    private Random rand = null;
    private int possibilityMax = 100;
    private int possibilityMin = 0;

    public LotteryPool() {
        try {
            rand = SecureRandom.getInstanceStrong();
        } catch (NoSuchAlgorithmException e) {
            log.error("LotteryPool.error", e);
        }
    }

    public void add(int possibility, T o) {
        if (possibility < possibilityMin) {
            possibility = possibilityMin;
        } else if (possibility > possibilityMax) {
            possibility = possibilityMax;
        }
        for (int i = 0; i < possibility; i++) {
            items.add(o);
        }
    }

    public T pick() {
        int index = rand.nextInt(items.size());
        if (index >= 0 && index < items.size()) {
            return items.get(index);
        }
        return null;
    }
}
